import axios from "axios";
import router from "../router/index.js";
import { Message } from "element-ui";

// const BASEURL =
//   process.env.NODE_ENV === "development"
//     ? process.env.VUE_APP_HTTP
//     : "http://101.132.103.213:4000/api";

// const BASEURL= "http://58.56.218.78:9000"

const service = axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    "Content-Type": "application/json; charset=utf-8",
    "Access-Control-Allow-Origin": "*"
  }
});

/**
 * 请求拦截
 */
service.interceptors.request.use(
  config => {
    config.headers["token"] = JSON.parse(localStorage.getItem("protal-token"));
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

/**
 * 响应拦截
 */
service.interceptors.response.use(
  response => {
    if (response.data && response.data.code === 401) {
      // 401, token失效
      Message({
        type: "warning",
        showClose: true,
        message: "未登录或登录超时，请重新登录哦"
      });
      localStorage.removeItem("token");
      router.push({ name: "login" });
    }
    if (response.data && response.data.code === 302) {
      Message({
        type: "warning",
        showClose: true,
        message: "没有访问权限"
      });
      router.push("/");
    }
    return response;
  },
  error => {
    Message({
      type: "warning",
      showClose: true,
      message: "未知异常,请联系管理员"
    });
    // Message.error(error.response.data)
    // if(error.status===404){
    //   router.push({ name: '404' })
    // }
    return Promise.reject(error);
  }
);

export default service;
